﻿@using ZR.CodeGenerator
@using ZR.Model.System.Generate
@using Infrastructure.Extensions;
@using Microsoft.AspNetCore.Mvc.Rendering
@using Microsoft.AspNetCore.Mvc.ViewFeatures
@* @model ZR.CodeGenerator.Model.GenerateDto; *@
@{
    var genTable = Model.GenTable;
    var genTableOptions = genTable.Options;
    List<GenTableColumn> listCols = genTable.ListItemColumns;
    List<GenTableColumn> opeFormCols = genTable.OpeFormColumns;
    List<GenTableColumn> formCols = genTable.FormColumns;
    List<GenTableColumn> queryFormCols = genTable.QueryFormColumns;

    var funCodeFirstLower = genTable.FunctionCode.FirstLowerCase();
    var isShowLeftTree = genTableOptions.IsShowLeftTree;
    var isTreeTableShowTree = genTableOptions.IsTreeTable && isShowLeftTree;

    string leftTreeDataName = null;
    string leftTreeApiName = null;
    string leftTreeApiImport = null;
    if (isShowLeftTree)
    {
        if (genTableOptions.LeftTreeComponent == "self")
        {
            leftTreeDataName = $"{funCodeFirstLower}TreeOptions";
            leftTreeApiName = $"get{genTable.FunctionCode}TreeSelectList";
        }
        else
        {
            leftTreeDataName = $"{genTableOptions.LeftTreeComponent}TreeOptions";
            switch (genTableOptions.LeftTreeComponent)
            {
                case "company":
                    leftTreeApiName = "getCompanyTreeSelectList";
                    leftTreeApiImport = "import { getCompanyTreeSelectList } from '@/api/baseFrame/base/company'";
                    break;
                case "dept":
                    leftTreeApiName = "getDepartTreeSelectList";
                    leftTreeApiImport = "import { getDepartTreeSelectList } from '@/api/baseFrame/base/depart'";
                    break;
                case "company_depart":
                    leftTreeApiName = "getOrgTreeSelectList";
                    leftTreeApiImport = "import { getOrgTreeSelectList } from '@/api/baseFrame/depart'";
                    break;
                default:
                    break;
            }
        }
    }

    var idFieldNameFirstLower = genTable.PkFieldName.FirstLowerCase();
    var subTableOptions = Model.SubTableOptions;
    var replaceDto = Model.ReplaceDto;
    bool showCustomInput = Model.GenTable.Columns.Any((Func<GenTableColumn, bool>)(f => f.HtmlType.Equals(GenConstants.HTML_CUSTOM_INPUT, StringComparison.OrdinalIgnoreCase)));
    var index = 0;
    var dictHtml = new string[] { GenConstants.HTML_CHECKBOX, GenConstants.HTML_RADIO, GenConstants.HTML_RADIO_BTN, GenConstants.HTML_SELECT, GenConstants.HTML_SELECT_MULTI };
    var dicts = new List<GenTableColumn>();
    dicts.AddRange(Model.GenTable.Columns.FindAll((Predicate<GenTableColumn>)(f => dictHtml.Contains(f.HtmlType))));
    if (Model.GenTable.SubTable != null && Model.GenTable.SubTableName.IsNotEmpty())
    {
        dicts.AddRange(Model.GenTable?.SubTable?.Columns?.FindAll((Predicate<GenTableColumn>)(f => dictHtml.Contains(f.HtmlType))));
    }
    var customCtls = opeFormCols.Where(m => m.HtmlType == "customCtl").Distinct().ToList();
    var iconCtls = formCols.Where(m => m.HtmlType == "icon").Distinct().ToList();
    var isHasIconCtl = iconCtls.Count > 0;
}

    import { 
        get@(genTable.FunctionCode)PageList,
        get@(genTable.FunctionCode)Detail,
@if(replaceDto.ShowBtnAdd)
{
        @:add@(genTable.FunctionCode),
}
@if (replaceDto.ShowBtnDelete || replaceDto.ShowBtnMultiDel)
{
        @:del@(genTable.FunctionCode),
}
@if (replaceDto.ShowBtnEdit)
{
        @:modify@(genTable.FunctionCode),
}
@if (genTableOptions.IsHasEnableStateField && genTableOptions.IsEnableStateChange)
{
        @:change@(genTable.FunctionCode)State,
}       
@if (genTableOptions.IsTreeTable)
{
        @:get@(genTable.FunctionCode)TreeSelectList
}
@if(replaceDto.ShowBtnExport)
{
        @:export@(genTable.FunctionCode)List,
}
@if(showCustomInput)
{
        @:changeSort
}
    } from '@@/api/@(CodeGeneratorTool.FirstLowerCase(genTable.ModuleCode))/base/@(funCodeFirstLower).js';
@if (isShowLeftTree && genTableOptions.LeftTreeComponent != "self")
{
    @:@(leftTreeApiImport)
}
    import Treeselect from '@@riophae/vue-treeselect'
    import '@@riophae/vue-treeselect/dist/vue-treeselect.css'
@if(isHasIconCtl)
{
    @:import IconSelect from '@@/components/IconSelect'
}
@foreach (var col in customCtls)
{
    string customCtl=col.CustomCtl;
    switch (customCtl)
    {
        case "companyTreeSelect":
    @:import { getCompanyTreeSelectList as @(customCtl)DataQuery } from '@@/api/baseFrame/base/company'
            break;
            case "orgDepartTreeSelect":
    @:import { getOrgTreeSelectList as @(customCtl)DataQuery } from '@@/api/baseFrame/depart'
            break;
    }
}

    export default {
        name: "@(genTable.FunctionCode.ToLower())",
        components: { Treeselect@(isHasIconCtl ? ",IconSelect" : "") },
        data() {
            return {
                labelWidth: "100px",
                formLabelWidth:"100px",
                // 选中@(replaceDto.FistLowerPk)数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 遮罩层
                loading: false,
                // 显示搜索条件
                showSearch: true,
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    sort: undefined,
                    sortType: undefined,
    @foreach(var item in queryFormCols)
    {
                    @:@(item.CsharpFieldFl): undefined,
    }
                },
    @if(genTableOptions.IsTreeTable)
    {
                // 字典树选项
                @:@(funCodeFirstLower)TreeFormOptions: undefined,           
    }
    @if (isShowLeftTree)
    {
                @:treeFilterKeywords:undefined,
                @:@(leftTreeDataName):undefined,
    }
                defaultTreeProps: {
                    children: 'children',
                    label: 'label',
                },
                noOptionsText: '暂无数据',
                noChildrenText: '暂无子项',
                noResultsText: '未找到匹配项',
                loadingText: '数据加载中...',
                // 弹出层标题
                title: "",
@foreach (var col in customCtls)
{
    string customCtl=col.CustomCtl;
                @:@(customCtl)FormOptions:undefined,
}
                // 操作类型 1、add 2、edit
                opertype: 0,
                // 是否显示弹出层
                open: false,
                // 表单参数
                form: {},
                columns: [
@{
    index = 0;
}
@foreach (var column in listCols)
{
                    @:{ index: @index, key: '@(column.CsharpFieldFl)', label: `@(column.FieldDesc)`, checked:  @(index < 9?"true":"false")  },
    if (genTableOptions.IsTreeTable && column.CsharpField == genTableOptions.TreeTableNodePaIdField)
    {
        index++;
                    @:{ index: @index, key: 'pa@(genTableOptions.TreeTableNodeNameField)', label: `上级`, checked:  @(index < 9 ? "true" : "false")  },
    }
    index = index + 1;
}
                ],
@foreach (var item in opeFormCols)
{
    if((item.HtmlType == "radio" || item.HtmlType == "radioBtn"  || item.HtmlType == "select" || item.HtmlType == "checkbox"))
    {
                @:// @(item.FieldDesc)选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
                @:@(item.DictType != ""?item.DictType:$"{item.CsharpFieldFl}Options"): [],
    }
    else if(item.HtmlType == "datetime" && item.IsQuery == true)
    {
                @://@(item.FieldDesc)时间范围
                @:dateRange@(item.CsharpField): [],
    }
    else if(item.HtmlType == "customInput")
    {
                @:editIndex: -1,
    }
}
                dataList: [],
                total: 0,
                rules: {
@if(replaceDto.ShowBtnAdd || replaceDto.ShowBtnEdit)
{
    foreach (var column in formCols)
    {
        if(column.IsRequired==true && column.IsIncrement == false)
        {
                    @:@(column.CsharpFieldFl): [{ required: true, message: "@(column.FieldDesc)不能为空", trigger: "@(column.HtmlType == "select"?"change":"blur")" }],
        }
    }
}
                },
            };
        },
        watch: {
@if (isShowLeftTree)
{
            @:// 根据名称筛选树结点
            @:treeFilterKeywords(val) {
                @:this.$refs.tree.filter(val)
            @:},
}
@foreach(var col in customCtls)
{
    string customCtl = col.CustomCtl;
    switch (customCtl)
    {
        case "orgDepartTreeSelect":
            @:'form.companyId':function(newVal, oldVal){
                @:this.form.paDepartId=undefined
                @:this.@(customCtl)DataQuery({'companyId':newVal,'isDefaultNodeType':false})
            @:}
            break;
    }
}
        },
        created() {
@if (isShowLeftTree)
{
            @:this.@(leftTreeApiName)()
}
@if(genTableOptions.IsTreeTable)
{
            @:this.@(funCodeFirstLower)FormTreeOptionsQuery()
}
            // 列表数据查询
            this.getList();
@{
    index = 0;
}
            var dictParams = [
@foreach (var item in dicts)
{
    @if (item.DictType != "")
    {
                @:"@(item.DictType)",
    }
    index = index + 1;
}
            ];
@if(index > 0)
{
            @:this.getDicts(dictParams).then((response) => {
                @:response.data.forEach((element) => {
                    @:this[element.dictType] = element.list;
                @:});
            @:});
}
@foreach (var col in customCtls)
{
    string customCtl=col.CustomCtl;
    string data = "{}";
    switch (customCtl)
    {
        case "companyTreeSelect":
            data = "{'IsReturnRoot':false,'OnlyLevel1Node':false}";
            break;
        case "orgDepartTreeSelect":
            data = "{'IsReturnRoot':false,'OnlyLevel1Node':false}";
            break;

    }
            @:this.@(customCtl)DataQuery(@(data));
}
        },
        methods: {
@foreach(var item in iconCtls)
{
            @:@(item.CsharpFieldFl)IconSelected(name) {
                @:this.form.@(item.CsharpFieldFl) = name
            @:},
}
            normalizer(node) {
                return {
                    id: node.id,
                    label: node.label,
                    children: node.children,
                    isDisabled: node.isDisabled==true || node.isDisabled=='True'
                };
            },
@if(genTableOptions.IsTreeTable)
{
            @:@(funCodeFirstLower)FormTreeOptionsQuery(){
                @:get@(genTable.FunctionCode)TreeSelectList({RootNodeName:'根结点',OnlyLevel1Node:@(genTableOptions.LeftTreeIsOnlyReturnRoot.ToString().ToLower())}).then((response) => {
                    @:this.@(funCodeFirstLower)TreeFormOptions = response.data
                @:})
            @:},
}
@if(isShowLeftTree)
{
            @:@(leftTreeApiName)() {
                @:@(leftTreeApiName)({OnlyLevel1Node:@(genTableOptions.LeftTreeIsOnlyReturnRoot.ToString().ToLower())}).then((response) => {
                    @:this.@(leftTreeDataName) = response.data
                @:})
            @:},

            @:// 节点单击事件
            @:handleNodeClick(data) {
                @:this.queryParams.treeNodeId = data.id
                @:this.queryParams.isDefaultNodeType=data.isDefaultNodeType
                @:this.getList()
            @:},
            @:// 筛选节点
            @:filterNode(value, data) {
                @:if (!value) return true
                @:return data.label.indexOf(value) !== -1
            @:},
}
            // 查询数据
            getList() {
@foreach (var item in queryFormCols)
{
    if(item.HtmlType == "datetime")
    {
                @:this.addDateRange(this.queryParams, this.dateRange@(item.CsharpField), '@(item.CsharpField)');
    }
}
                this.loading = true;
                get@(genTable.FunctionCode)PageList(this.queryParams).then(res => {
                    if (res.code == 200) {
                        this.dataList = res.data.result;
                        this.total = res.data.totalNum;
                        this.loading = false;
                    }
                })
            },
@foreach(var col in customCtls)
{
    string customCtl=col.CustomCtl;
            @:@(customCtl)DataQuery(data) {
                @:@(customCtl)DataQuery(data).then((response) =>
                @:{
                    @:this.@(customCtl)FormOptions = response.data
                @:})
            @:},
            @:handle@(customCtl)Selected(node)
            @:{

            @:},
}

            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 重置数据表单
            reset() {
                this.form = {
@foreach(var item in formCols)
{
    if(item.HtmlType == "checkbox")
    {
                    @:@(item.CsharpFieldFl)Checked: [],
    }
    else
    {
        var colInitVal = "undefined";
        switch(item.CsharpFieldFl)
        {
            case "sortNo":
                colInitVal = "100";
                break;
            case "stateCode":
                colInitVal = "'Enabled'";
                break;
            default:
                break;
        }
                    @:@item.CsharpFieldFl: @(colInitVal),
    }
}
                };
                this.resetForm("form");
            },
            // 重置查询操作
            resetQuery() {
                this.timeRange = [];
@foreach (var item in queryFormCols)
{
    if(item.HtmlType == "datetime")
    {
                @://@(item.FieldDesc)时间范围
                @:this.dateRange@(item.CsharpField)= [];
    }
}
                this.resetForm("queryForm");
                this.queryParams.treeNodeId=undefined;
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                    this.ids = selection.map((item) => item.@(replaceDto.FistLowerPk));
                    this.single = selection.length != 1
                    this.multiple = !selection.length;
            },
            // 自定义排序
            sortChange(column) {
                    if (column.prop == null || column.order == null) {
                        this.queryParams.sort = undefined;
                        this.queryParams.sortType = undefined;
                    } else {
                        this.queryParams.sort = column.prop;
                        this.queryParams.sortType = column.order;
                    }

                    this.handleQuery();
            },
@if(genTableOptions.IsEnableStateChange)
{
            @:handleStatusChange(row) {
                @:let text = row.stateCode == 'Enabled' ? '启用' : '禁用'
                @:this.$confirm('确认要' + text + '吗?', '警告', {
                    @:confirmButtonText: '确定',
                    @:cancelButtonText: '取消',
                    @:type: 'warning',
                @:})
                @:.then(function () {
                    @:return change@(genTable.FunctionCode)State({ "id": row.@(idFieldNameFirstLower), "stateCode": row.stateCode })
                @:})
                @:.then(() => {
                    @:this.msgSuccess(text + '成功')
                @:})
                @:.catch(function () {
                    @:row.stateCode = row.stateCode == 'Disabled' ? 'Enabled' : 'Disabled'
                @:})
            @:},
}
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
@if (replaceDto.ShowBtnAdd)
{
            @:/** 新增按钮操作 */
            @:handleAdd() {
                @:this.reset();
                @:this.open = true;
                @:this.title = "添加";
                @:this.opertype = 1;
    @if(genTableOptions.IsShowLeftTree)
    {
        if (genTableOptions.LeftTreeComponent=="self")
        {
                @:this.form.@(genTableOptions.TreeTableNodePaIdField.FirstLowerCase())=this.queryParams.treeNodeId||0;
        }
        else
        {
                if(genTableOptions.LeftTreeComponent=="company_depart")
                {
                @:if(!this.queryParams.isDefaultNodeType)
                @:{
                    @:if(this.queryParams.treeNodeId>0)
                    @:{
                        @:this.form.companyId=this.queryParams.treeNodeId||undefined;
                    @:}
                @:}
                @:else
                @:{
                    @:this.form.companyId=undefined;
                    @:this.form.departId=this.queryParams.treeNodeId||undefined;
                @:}
                }
                else
                {
                @:this.form.@(genTableOptions.LeftTreeNodeIdField.FirstLowerCase())=this.queryParams.treeNodeId||undefined;
                }
            if(genTableOptions.IsTreeTable)
            {
                @:if(this.queryParams.isDefaultNodeType)
                @:{
                    @:this.form.@(genTableOptions.TreeTableNodePaIdField.FirstLowerCase())=this.queryParams.treeNodeId||0;
                @:}
            }
        }
    }
            @:},
}

@if (replaceDto.ShowBtnDelete || replaceDto.ShowBtnMultiDel)
{
            @:/** 删除按钮操作 */
            @:handleDelete(row) {
                    @:const Ids = row.@(replaceDto.FistLowerPk) || this.ids;

                    @:var confirmTip='确认要删除数据项吗？';
                    @:if(row.dataName)
                    @:{
                            @:confirmTip='确认要删除数据项吗？';
                    @:}
                    @:this.$confirm(confirmTip)
                    @:.then(function () {
                        @:return del@(genTable.FunctionCode)({"Ids":Ids+''});
                    @:})
                    @:.then(() => {
                        @:this.handleQuery();
    @if(isTreeTableShowTree)
    {
                        @:this.@(leftTreeApiName)();
    }
                        @:this.msgSuccess("删除成功");
                    @:})
                    @:.catch(() => {});
            @:},
}

@if (replaceDto.ShowBtnEdit)
{
            @:/** 修改按钮操作 */
            @:handleUpdate(row) {
                @:this.reset();
                @:const id = row.@(replaceDto.FistLowerPk) || this.ids;
                @:get@(genTable.FunctionCode)Detail(id).then((res) => {
                        @:const { code, data } = res;
                        @:if (code == 200) {
                                @:this.open = true;
                                @:this.title = "修改数据";
                                @:this.opertype = 2;

                                @:this.form = {
                                    @:...data,
@foreach(var item in formCols)
{
    if(item.HtmlType == "checkbox")
    {
                                    @:@(item.CsharpFieldFl)Checked: data.@(item.CsharpFieldFl) ? data.@(item.CsharpFieldFl).split(',') : [],
    }
}
                                @:};
                        @:}
                    @:});
                @:},
}

@if(replaceDto.UploadFile == 1)
{
                @://图片上传成功方法
                @:handleUploadSuccess(column, filelist) {
                        @:this.form[column] = filelist;
                @:},
}
@foreach(var item in formCols)
{
    if(item.HtmlType == "customInput")
    {
                @:// 显示编辑排序
                @:editCurrRow(rowId, str) {
                    @:this.editIndex = rowId;
                    @:let id = rowId + str;
                    @:setTimeout(() => {
                        @:document.getElementById(id).focus();
                    @:}, 100);
                @:},
                @:// 保存排序
                @:handleChangeSort(info) {
                    @:this.editIndex = -1;
                    @:changeSort({ value: info.@(item.CsharpFieldFl), id: info.@(replaceDto.FistLowerPk) }).then(
                    @:(response) => {
                        @:this.msgSuccess("修改成功");
                        @:this.getList();
                    @:}
                    @:);
                @:},
    }
}

@if(replaceDto.ShowBtnAdd || replaceDto.ShowBtnEdit)
{
                @:/** 提交按钮 */
                @:submitForm: function () {
                    @:this.$refs["form"].validate((valid) => {
                        @:if (valid) {
@foreach(var item in formCols)
{
    if(item.HtmlType == "checkbox")
    {
                            @:this.form.@(item.CsharpFieldFl) = this.form.@(item.CsharpFieldFl)Checked.toString();
    }
}
                            @:if (this.form.@(replaceDto.FistLowerPk) != undefined && this.opertype === 2) {
                                @:modify@(genTable.FunctionCode)(this.form)
                                    @:.then((res) => {
                                        @:this.msgSuccess("修改成功");
                                        @:this.open = false;
                                        @:this.getList();
@if(isTreeTableShowTree)
{
                                        @:this.@(leftTreeApiName)();
    }
                                    @:})
                            @:}
                            @:else {
                                @:add@(genTable.FunctionCode)(this.form)
                                    @:.then((res) => {
                                    @:this.msgSuccess("新增成功");
                                    @:this.open = false;
                                    @:this.getList();
@if(isTreeTableShowTree)
{
                                    @:this.@(leftTreeApiName)();
    }
                                @:})
                            @:}
                        @:}
                    @:});
                @:},
}

@if(replaceDto.ShowBtnExport)
{
                @:/** 导出按钮操作 */
                @:handleExport() {
                    @:const queryParams = this.queryParams;
                    @:this.$confirm("是否确认导出所有@(genTable.FunctionName)数据项?", "警告", {
                            @:confirmButtonText: "确定",
                            @:cancelButtonText: "取消",
                            @:type: "warning",
                    @:}).then(async () => {
                            @:await export@(genTable.FunctionCode)List(queryParams);
                    @:})
                @:},
}
    },
};